<?php
/**
 * Created by PhpStorm.
 * User: 9ey
 * Date: 2019/5/24
 * Time: 17:36
 */

namespace App\Service;


use Illuminate\Support\Facades\File;

class BaseApiService
{
    protected function post($url, $params)
    {
        $this->apiLog($url, true);
        $this->apiLog(json_encode($params, JSON_UNESCAPED_UNICODE));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $error = curl_error($curl);
        $this->apiLog($error);
        curl_close($curl);
        $this->apiLog($res);
        return $res;
    }

    protected function get($url, $params)
    {
        $url = $url . "?" . http_build_query($params);
        $this->apiLog($url, true);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $error = curl_error($curl);
        if ($error) {
            $this->apiLog($error);
        }
        curl_close($curl);
        $this->apiLog($res);
        return $res;
    }

    protected function apiLog($content, $isFirst = false)
    {
        if ($isFirst) {
            $content = PHP_EOL . '[' . date('Y-m-d H:i:s') . ']' . $content;
        }
        $content .= PHP_EOL;
        $directory = storage_path('api_logs');
        if (!File::exists($directory)) {
            File::makeDirectory($directory, 0777, true);
        }
//        dump($directory . DIRECTORY_SEPARATOR . date('Ymd') . '.log');
        error_log($content, 3, $directory . DIRECTORY_SEPARATOR . date('Ymd') . '.log');
    }
}